<?php
declare (strict_types=1);
namespace app\common\controller;
//use app\admin\model\Category;
use app\BaseController;
use app\common\UserVisitor;
use app\home\model\Nav as NavModel;
use think\facade\Config;
use think\facade\Db;
use think\facade\View;
use app\home\model\Config as ConfigModel;

class Frontend extends BaseController
{
    protected $mold;
    protected $home_tplpath;
    public function initialize() {
        parent::initialize();
        try {
            //网站配置缓存
            $web_config =   cache('web_config');
            if(!$web_config){
                $web_config = config_lists();
                cache('web_config', $web_config);
            }
           Config::set($web_config,'web_config');
        }catch(Exception $e){

        }

        if(!config('web_config.site_status')){
           return config('web_config.closed_reason');
        }

        $actionname = strtolower(request()->action());
        if ($actionname != 'doccon') {
            $cssnum = 1;
            View::assign('cssnum', $cssnum);
        }

        $modulename = strtolower(request()->controller());
        View::assign('modulename', $modulename);
        View::assign('actionname', $actionname);

        //初始化访问者
        $this->_init_visitor();
        global $userinfo;
        $userinfo = $this->visitor->info;
        View::assign('uid', $userinfo['id']);
//        var_dump(empty(cache('nav_list')));exit;
        //网站主导航与底部导航加载
        if (empty(cache('nav_list'))) {
            $nav_mod = new NavModel();
            $navlist = $nav_mod->nav_cache();
        }
        //网站配置缓存
        if (empty(cache('web_config'))) {
            $this->_mod  = new \app\admin\model\Config();
            $data = $this->_mod->field('name,value')->select();
            foreach ($data as $key=>$val) {
                $val_data = $val->value;
                $web_config[$val->name] = @unserialize($val_data)?unserialize($val_data):$val_data;
            }
            cache('web_config', $web_config);
        }

        View::assign('navlist', cache('nav_list'));
//        if ($state) {
//            $cate = Db::name('category')->where(array('pid' => 0, 'status' => 1))->select();
//            if ($cate) {
//                View::assign('cate', $cate);
//            }
//        }

        //网站导航选中
        View::assign('nav_curr', '');
        //友情链接
        $maplink['status'] = 1;
        $flink= Db::name('flink')->where($maplink)->order('ordid')->select();
        foreach ($flink as $k => $v) {
            if (strpos($flink[$k]['url'], 'http')===false) {
                $flink[$k]['url']='http://'.$flink[$k]['url'];
            }
        }
        View::assign('flink', $flink);
        $id = request()->param('id')?request()->param('id'):0;
        View::assign('id', $id);
        //友情链接
        $maplink['status'] = 1;
        $flink= Db::name('flink')->where($maplink)->order('ordid')->select();
        foreach ($flink as $k => $v) {
            if (strpos($flink[$k]['url'], 'http')===false) {
                $flink[$k]['url']='http://'.$flink[$k]['url'];
            }
        }
        View::assign('flink', $flink);
        $seoconfig = $this->_config_seo(config('web_config.seo_config.index'));
        View::assign('seoconfig', $seoconfig);
//        $_api_visitor= new UserVisitor();
    }

    /**
     * 初始化访问者
     */
    private function _init_visitor() {
        $this->visitor = new UserVisitor();
        View::assign('visitor', $this->visitor->info);
    }

    /**
     * SEO设置
     */
    protected function _config_seo($seo_info = [], $data = []) {
        $web_config= cache('web_config');
        $page_seo = [
            'title' =>$web_config['site_title'],
            'keywords' => $web_config['site_keyword'],
            'description' => $web_config['site_description']
        ];

        $page_seo = array_merge($page_seo, $seo_info);
        //开始替换
        $searchs = array('{site_name}', '{site_title}', '{site_keywords}', '{site_description}');
        $replaces = array($web_config['site_name'], $web_config['site_title'],$web_config['site_keyword'],$web_config['site_description']);
        preg_match_all("/\{([a-z0-9_-]+?)\}/", implode(' ', array_values($page_seo)), $pageparams);
        if ($pageparams) {
            foreach ($pageparams[1] as $var) {
                $searchs[] = '{' . $var . '}';
                $replaces[] = $data[$var] ? strip_tags($data[$var]) : '';
            }
            //符号
            $searchspace = array('((\s*\-\s*)+)', '((\s*\,\s*)+)', '((\s*\|\s*)+)', '((\s*\t\s*)+)', '((\s*_\s*)+)');
            $replacespace = array('-', ',', '|', ' ', '_');
            foreach ($page_seo as $key => $val) {
                $page_seo[$key] = trim(preg_replace($searchspace, $replacespace, str_replace($searchs, $replaces, $val)), ' ,-|_');
            }
        }
        return $page_seo;
    }

    /**
     * 获取请求参数生成条件数组
     */
    protected function _search($Fields) {
        $map =[];
        //生成查询条件
        foreach ($Fields as $key => $val) {

            if (request()->param($val)) {
                $map[$val] = request()->param($val);
            }
        }
        return $map;
    }


    protected function _list( $model, $map = array(), $sort_by = '', $order_by = '', $field_list = '*', $pagesize = 15) {
        //排序
        $data = array();
        $mod_pk = $model->getPk();
        if (request()->param("sort")) {
            $sort = trim(request()->param("sort"));
        } else if (!empty($sort_by)) {
            $sort = $sort_by;
        } else {
            $sort = $mod_pk;
        }
        if (request()->param("order")) {
            $order = trim(request()->param("order"));
        } else if (!empty($order_by)) {
            $order = $order_by;
        } else {
            $order = 'DESC';
        }
        //如果需要分页
        if ($pagesize) {
            $list = $model->field($field_list)->where($map)->order($sort . ' ' . $order)->paginate([
                'list_rows'     =>  $pagesize,
                'query'         =>  request()->param()
            ]);
        }else{
            $list = $model->field($field_list)->where($map)->order($sort . ' ' . $order)->select();
        }
        View::assign('list', $list);
        $data['list'] = $list;
        $data['list_table'] = 1;
        return $data;
    }
}